<template>
  <div class="aging-test-home">
    <!-- 首页视图 -->
    <div v-if="currentView === 'home'" class="home-view">
      <!-- 统计卡片区域 -->
      <div class="stat-cards">
        <el-card class="stat-card">
          <div class="stat-title">测试中</div>
          <div class="stat-value primary">{{ testingCount }}</div>
          <div class="stat-footer">
            <el-tag size="small" type="primary">进行中</el-tag>
          </div>
        </el-card>

        <el-card class="stat-card">
          <div class="stat-title">测试完成率</div>
          <div class="stat-value secondary">{{ completionRate }}%</div>
          <div class="stat-footer">
            <el-tag size="small" type="success">完成率</el-tag>
          </div>
        </el-card>

        <el-card class="stat-card">
          <div class="stat-title">测试完成</div>
          <div class="stat-value success">{{ completedCount }}</div>
          <div class="stat-footer">
            <el-tag size="small" type="success">已完成</el-tag>
          </div>
        </el-card>
      </div>

      <!-- 老化测试任务表格 -->
      <el-card class="task-table-card">
        <!-- 筛选框区域 -->
        <div class="filter-container">
          <el-form :inline="true" class="filter-form">
            <el-form-item label="测试状态:">
              <el-select v-model="testStatus" placeholder="请选择测试状态" clearable @change="queryAgingTest" filterable>
                <el-option label="测试中" value="测试中"></el-option>
                <el-option label="测试完成" value="测试完成"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="产品名称:">
              <el-select v-model="productName" placeholder="请选择产品名称" clearable @change="queryAgingTest" filterable>
                <el-option label="LED灯泡" value="LED灯泡"></el-option>
                <el-option label="LED灯管" value="LED灯管"></el-option>
                <el-option label="LED面板灯" value="LED面板灯"></el-option>
                <el-option label="LED射灯" value="LED射灯"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="handleReset" type="warning">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-table :data="tableData" style="width: 100%" border>
          <el-table-column prop="testId" label="测试单ID" width="150"></el-table-column>
          <el-table-column prop="productName" label="产品名称" width="150"></el-table-column>
          <el-table-column prop="testStatus" label="当前状态">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.testStatus)">{{ scope.row.testStatus }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="开始时间" width="180"></el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button type="primary" size="small" @click="viewDetail(scope.row)">详情</el-button>
              <el-button v-if="scope.row.testStatus !== '测试完成'" type="success" size="small" @click="reviewTaskBox(scope.row.testId)">测试完成</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <div class="total-info">共{{ total }}条记录</div>
          <el-pagination v-model:current-page="currentPage" :page-sizes="[10, 20, 30, 50]" v-model:page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange">
          </el-pagination>
        </div>
      </el-card>
    </div>

    <!-- 详情视图 -->
    <div v-if="currentView === 'detail'" class="detail-view">
      <!-- 测试基本信息卡片 -->
      <el-card class="info-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <div class="header-left">
              <el-icon class="header-icon">
                <Document />
              </el-icon>
              <h2>老化测试详情</h2>
            </div>
            <div class="header-right">
              <el-tag :type="getStatusType(testDetail.testStatus)" size="large">
                {{ testDetail.testStatus }}
              </el-tag>
              <el-button type="primary" @click="goBackToHome" style="margin-left: 10px;">
                <el-icon>
                  <ArrowLeft />
                </el-icon>
                返回列表
              </el-button>
              <el-button v-if="!isEditing && testDetail.testStatus === '测试中'" type="danger" @click="enableEdit">
                <el-icon>
                  <Edit />
                </el-icon>
                编辑
              </el-button>
            </div>
          </div>
        </template>

        <el-form :model="testDetail" label-width="120px" class="detail-form">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="测试单ID:">
                <el-input v-model="testDetail.testId" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工程师ID:">
                <el-input v-model="testDetail.engineerId" :disabled="!isEditing"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="产品名称:">
                <el-select v-model="testDetail.productName" :disabled="!isEditing" placeholder="请选择产品名称">
                  <el-option label="LED灯泡" value="LED灯泡"></el-option>
                  <el-option label="LED灯管" value="LED灯管"></el-option>
                  <el-option label="LED面板灯" value="LED面板灯"></el-option>
                  <el-option label="LED射灯" value="LED射灯"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="测试状态:">
                <el-select v-model="testDetail.testStatus" :disabled="!isEditing" placeholder="请选择测试状态">
                  <el-option label="测试中" value="测试中"></el-option>
                  <el-option label="测试完成" value="测试完成"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="测试时长:">
                <el-input v-model="testDetail.duration" :disabled="!isEditing" type="number" placeholder="请输入测试时长">
                  <template #append>小时</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="检验ID:">
                <el-input v-model="testDetail.inspectionId" :disabled="!isEditing" placeholder="请输入检验ID"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="创建时间:">
                <el-input v-model="testDetail.createTime" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="更新时间:">
                <el-input v-model="testDetail.updateTime" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注:">
                <el-input v-model="testDetail.remarks" :disabled="!isEditing" type="textarea" :rows="3"
                  placeholder="请输入备注信息"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <!-- 测试数据卡片 -->
      <el-card class="data-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon class="header-icon">
              <DataAnalysis />
            </el-icon>
            <h2>测试数据</h2>
          </div>
        </template>

        <el-form :model="testDetail" label-width="120px" class="detail-form">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="测试时长:">
                <el-input v-model="testDetail.duration" :disabled="!isEditing" type="number" placeholder="请输入测试时长">
                  <template #append>小时</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="光衰减率:">
                <el-input v-model="testDetail.lumenDepreciation" :disabled="!isEditing" type="number"
                  placeholder="请输入光衰减率">
                  <template #append>%</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="光衰减详细数据:">
                <div class="data-actions">
                  <el-button type="primary" size="small" @click="viewJsonData">
                    查看详细数据
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>

    <!-- JSON数据查看对话框 -->
    <el-dialog v-model="jsonDialogVisible" title="光衰减详细数据" width="60%">
      <el-input v-model="testDetail.lightDecay" type="textarea" :rows="10" readonly placeholder="暂无数据" />
      <template #footer>
        <el-button @click="jsonDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, computed } from 'vue'
import * as echarts from 'echarts'
import { useRouter } from 'vue-router'
import { queryAgingTestService, updateAgingTestService, successAgingTestService } from '@/api/InspectApi'
import {
  Document,
  DataAnalysis,
  Lightning,
  Timer,
  Sunny,
  View,
  Upload,
  Edit,
  TrendCharts,
  ArrowLeft
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()

// 视图切换控制
const currentView = ref('home') // 'home' | 'detail'
const selectedTestData = ref(null)

// 编辑状态控制
const isEditing = ref(false)
const saving = ref(false)
const originalTestDetail = ref(null)

// 对比显示控制
const showComparison = ref(false)

// 图表相关
const agingChart = ref()
let agingChartInstance: echarts.ECharts | null = null

// 老化趋势数据
const agingData = ref({
  dates: ['12-01', '12-02', '12-03', '12-04', '12-05', '12-06', '12-07', '12-08', '12-09'],
  values: [2.5, 2.2, 2.3, 1.8, 2.0, 1.5, 1.8, 1.2, 0.8]
})

// 表格数据
const tableData = ref([
  {
    testId: 'BATCH-0014',
    productName: 'LED灯芯',
    testStatus: '测试中',
    createTime: 'XXXX-XX-XX',
    duration: '',
    voltage: '',
    temperature: '',
    lumenDepreciation: '',
    remarks: '',
    lightDecay: ''
  }
])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(5)

//筛选数据
const testStatus = ref('')
const productName = ref('')

// 统计数据计算
const testingCount = computed(() => {
  return tableData.value.filter(item => item.testStatus === '测试中').length
})

const completedCount = computed(() => {
  return tableData.value.filter(item => item.testStatus === '测试完成').length
})

const completionRate = computed(() => {
  const totalCount = tableData.value.length
  if (totalCount === 0) return 0
  const completed = completedCount.value
  return Math.round((completed / totalCount) * 100)
})

// 获取状态对应的类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    '测试中': 'primary',
    '测试完成': 'success',
    '未测试': 'info',
    '异常': 'danger'
  }
  return statusMap[status] || 'info'
}

// 详情对话框相关
const jsonDialogVisible = ref(false)

// 测试详情数据
const testDetail = ref({
  testId: '',
  engineerId: '',
  productName: '',
  testStatus: '',
  duration: 0,
  voltage: 0,
  temperature: 0,
  lumenDepreciation: 0,
  lightDecay: '',
  inspectionId: null,
  remarks: '',
  createTime: '',
  updateTime: ''
})

// 查看详情
const viewDetail = (row: any) => {
  selectedTestData.value = row
  currentView.value = 'detail'
  // 根据testID获取详细数据
  //loadTestDetail(row.testID)
  Object.keys(testDetail.value).forEach(key => {
    if (row[key] !== undefined) {
      (testDetail.value as any)[key] = row[key]
    }
  })
}

// 审核任务
const reviewTask = async (testId: string) => {
  let params = {
    testId: testId
  }
  const result = await successAgingTestService(params) as any
  ElMessage.success(result.msg || '保存成功')
  queryAgingTest()
}

//审核任务弹窗
const reviewTaskBox = (testId: string) => {
  ElMessageBox.confirm(
    '确定审核通过该测试任务？（无法撤销）',
    '温馨提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      //审核任务
      reviewTask(testId)
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}

// 导出数据
const exportData = () => {
  console.log('导出数据')
}

// 获取老化测试数据
const queryAgingTest = async () => {
  let params = {
    testStatus: testStatus.value,
    productName: productName.value,
    pageNumber: currentPage.value,
    pageSize: pageSize.value
  }
  const result = await queryAgingTestService(params) as any
  tableData.value = result.data.records
  total.value = result.data.total
}
// 筛选处理函数

const handleReset = () => {
  testStatus.value = ''
  productName.value = ''
  currentPage.value = 1
  queryAgingTest()
}

// 分页处理
const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize
  queryAgingTest()
}

const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage
  queryAgingTest()
}

// 返回首页
const goBackToHome = () => {
  currentView.value = 'home'
  selectedTestData.value = null
  isEditing.value = false
  originalTestDetail.value = null
  nextTick(() => {
    initAgingChart()
  })
}

// 启用编辑
const enableEdit = () => {
  // 保存原始数据用于取消时恢复
  originalTestDetail.value = JSON.parse(JSON.stringify(testDetail.value))
  isEditing.value = true
}

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false
  // 恢复原始数据
  if (originalTestDetail.value) {
    Object.keys(testDetail.value).forEach(key => {
      if (originalTestDetail.value && originalTestDetail.value[key] !== undefined) {
        (testDetail.value as any)[key] = (originalTestDetail.value as any)[key]
      }
    })
  }
  originalTestDetail.value = null
}

// 保存详情数据
const saveDetailData = async () => {
  saving.value = true
  const result = updateAgingTestService(testDetail) as any
  ElMessage.success(result.msg || '保存成功')
  isEditing.value = false
  queryAgingTest()
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '未设置'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 查看JSON数据
const viewJsonData = () => {
  jsonDialogVisible.value = true
}

// 详情页面的上传附件
const uploadDetailAttachment = () => {
  console.log('上传测试附件 - 测试ID:', testDetail.value.testId)
}

// 详情页面的录入测试数据
const enterDetailTestData = () => {
  console.log('录入测试数据 - 测试ID:', testDetail.value.testId)
}

// 详情页面的生成趋势图
const generateDetailTrendChart = () => {
  console.log('生成趋势图 - 测试ID:', testDetail.value.testId)
  router.push(`/inspector/aging-test-trend?id=${testDetail.value.testId}`)
}

// 初始化老化趋势图
const initAgingChart = () => {
  if (!agingChart.value) return

  agingChartInstance = echarts.init(agingChart.value)

  const option = {
    title: {
      text: '老化趋势分析',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const param = params[0]
        return `${param.axisValue}<br/>老化指数: ${param.value}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: agingData.value.dates,
      axisLabel: {
        fontSize: 12
      }
    },
    yAxis: {
      type: 'value',
      name: '老化指数',
      axisLabel: {
        fontSize: 12
      }
    },
    series: [{
      name: '老化指数',
      type: 'line',
      data: agingData.value.values,
      smooth: true,
      lineStyle: {
        color: '#FF9900',
        width: 2
      },
      itemStyle: {
        color: '#FF9900'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0, color: 'rgba(255, 153, 0, 0.3)'
          }, {
            offset: 1, color: 'rgba(255, 153, 0, 0.1)'
          }]
        }
      }
    }]
  }

  agingChartInstance.setOption(option)

  // 响应式调整
  window.addEventListener('resize', () => {
    agingChartInstance?.resize()
  })
}

// 组件挂载后初始化图表和数据
onMounted(() => {
  nextTick(() => {
    initAgingChart()
    queryAgingTest()
  })
})
</script>

<style lang="scss" scoped>
.aging-test-home {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.filter-container {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.filter-form {
  margin: 0;
}

.filter-form .el-form-item {
  margin-bottom: 0;
  margin-right: 20px;
}

// 详情视图样式
.detail-view {
  .detail-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
    padding: 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 12px;
    color: white;
  }

  .detail-title {
    margin-left: 10px;
    font-size: 1.5rem;
    font-weight: bold;
  }

  .detail-actions {
    display: flex;
    gap: 10px;
  }

  .detail-form {
    padding: 20px;
  }

  .edit-actions {
    display: flex;
    justify-content: center;
    gap: 20px;
    padding: 20px;
  }

  .back-btn {
    color: white !important;
    border: 1px solid rgba(255, 255, 255, 0.3) !important;
    background: rgba(255, 255, 255, 0.1) !important;
  }

  .back-btn:hover {
    background: rgba(255, 255, 255, 0.2) !important;
  }

  .info-card,
  .data-card,
  .action-card {
    margin-bottom: 20px;
    border-radius: 12px;
    overflow: hidden;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
    }

    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 20px;
      margin: -20px -20px 20px -20px;

      .header-left {
        display: flex;
        align-items: center;
        gap: 12px;

        .header-icon {
          font-size: 24px;
        }

        h2 {
          margin: 0;
          font-size: 20px;
          font-weight: 600;
        }
      }

      .header-right {
        display: flex;
        align-items: center;
        gap: 10px;
      }
    }
  }

  .info-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
    padding: 10px;

    .info-item {
      display: flex;
      align-items: center;
      padding: 15px;
      background: linear-gradient(135deg, #f8f9ff 0%, #e8f4fd 100%);
      border-radius: 8px;
      border-left: 4px solid #409eff;
      transition: all 0.3s ease;

      &:hover {
        transform: translateX(5px);
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
      }

      &.full-width {
        grid-column: 1 / -1;
        flex-direction: column;
        align-items: flex-start;
      }

      label {
        font-weight: 600;
        color: #606266;
        margin-right: 10px;
        min-width: 80px;
      }

      .value {
        color: #303133;
        font-weight: 500;
      }
    }
  }

  .data-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
    padding: 10px;

    .data-item {
      background: linear-gradient(135deg, #fff5f5 0%, #fef0f0 100%);
      border-radius: 12px;
      padding: 20px;
      text-align: center;
      border: 2px solid #fde2e2;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 25px rgba(245, 101, 101, 0.2);
        border-color: #f56565;
      }

      &.full-width {
        grid-column: 1 / -1;
      }

      .data-label {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        margin-bottom: 12px;
        font-weight: 600;
        color: #606266;

        .el-icon {
          font-size: 18px;
          color: #f56565;
        }
      }

      .data-value {
        font-size: 24px;
        font-weight: bold;
        color: #303133;

        &.voltage {
          color: #e6a23c;
        }

        &.temperature {
          color: #f56c6c;
        }

        &.lumen {
          color: #67c23a;
        }
      }

      .data-actions {
        margin-top: 10px;
      }
    }
  }

  .action-card {
    .action-buttons {
      display: flex;
      justify-content: center;
      gap: 20px;
      flex-wrap: wrap;
      padding: 20px;

      .el-button {
        min-width: 160px;
        height: 50px;
        font-size: 16px;
        border-radius: 25px;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
        }
      }
    }
  }
}

// 首页视图样式
.home-view {
  .stat-cards {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;

    .stat-card {
      flex: 1;

      .stat-title {
        font-size: 14px;
        color: #909399;
        margin-bottom: 10px;
      }

      .stat-value {
        font-size: 28px;
        font-weight: bold;
        margin-bottom: 10px;

        &.primary {
          color: #333;
        }

        &.secondary {
          color: #333;
        }

        &.danger {
          color: #333;
        }
      }

      .stat-footer {
        font-size: 12px;

        .comparison {
          color: #909399;
        }
      }
    }
  }

  .task-table-card {
    margin-bottom: 20px;

    .pagination-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 20px;

      .total-info {
        font-size: 14px;
        color: #606266;
      }
    }
  }

  .trend-chart-card {
    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      h3 {
        margin: 0;
        font-size: 16px;
      }

      .chart-controls {
        display: flex;
        align-items: center;
        gap: 15px;
      }
    }

    .chart-container {
      display: flex;

      .chart-info {
        display: flex;
        flex-direction: column;
        margin-right: 10px;

        .chart-title {
          font-size: 12px;
          color: #909399;
          margin-bottom: 10px;
          text-align: center;
        }

        .chart-y-axis {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          height: 200px;
          font-size: 12px;
          color: #909399;
        }
      }

      .chart-content {
        flex: 1;

        .chart-legend {
          display: flex;
          justify-content: center;
          margin-top: 10px;

          .legend-item {
            display: flex;
            align-items: center;
            margin-right: 20px;

            .legend-color {
              display: inline-block;
              width: 12px;
              height: 12px;
              margin-right: 5px;
              border-radius: 2px;
            }
          }
        }
      }
    }
  }

  // 详情对话框样式
  :deep(.el-dialog) {
    .el-dialog__header {
      background-color: #f5f7fa;
      border-bottom: 1px solid #e4e7ed;
    }

    .el-dialog__body {
      padding: 20px;
    }

    .detail-pagination-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 20px 0;

      .total-info {
        font-size: 14px;
        color: #606266;
      }
    }

    .dialog-footer {
      display: flex;
      justify-content: center;
      gap: 15px;
    }
  }
}
</style>